package DAL;
import com.mysql.jdbc.StatementImpl;
import java.sql.*;

public class SqlHelper {
    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/servletdata?useSSL=true&characterEncoding=utf-8&user=root&password=");
            System.out.println("数据库连接成功！");
            System.out.println("-------------------------------");
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("创建连接失败！");
        System.out.println("-------------------------------");
        return null;
    }
    //select
    public static ResultSet executeQuery(String SQL)
    {
        try
        {
            Connection conn=getConnection();
            Statement stmt=conn.createStatement();
            ResultSet rs=stmt.executeQuery(SQL);
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询失败！");
            System.out.println("-------------------------------");
            return null;
        }
    }
    //insert update delete
    public static boolean executeUpdate(String SQL)
    {
        try
        {
            Connection conn=getConnection();
            Statement stmt=conn.createStatement();
            int rs=stmt.executeUpdate(SQL);
            if (rs>0)
                return true;
            else
                return false;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("更新失败！");
            System.out.println("-------------------------------");
            return false;
        }
    }
    public static void ShutDown(StatementImpl statement, Connection connection) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
}

